<template>
  <el-dialog v-model="openBoole" :close-on-click-modal="false" custom-class="mydialog" title="关联配送终端" width="50%"
    @close="close">
    <el-form ref="openRef" :model="openForm" :rules="rules" label-width="110px" size="small">
      <el-row gutter="40">
        <el-col :span="24">
          <el-form-item label="产品信息：">
            {{ getProductName(rowData) }}
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="代理名称：">
            {{ rowData?.agentName }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="代理地区：">
            <area-list-view :areas="rowData?.region" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="可营销终端：">
            {{ getLabel('app_mode', rowData.terminalType) }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责营销职员：">
            {{ rowData.headName }}
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="配送模式：">
            <el-radio v-model="openForm.rddType" label="2" size="large">配送商配送</el-radio>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-row gutter="40">
            <el-col :span="16">
              <el-form-item label="配送商" prop="distributeId">
                <el-select v-model="openForm.distributeId" placeholder="请选择配送商" style="width: 100%"
                  @change="distributesChange">
                  <el-option v-for="item in distributes" :key="item.id" :label="item.distributeName" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label-width="0">
                <span style="padding-right: 30px">没有找到签约配送商</span>
                <el-button type="text" @click="handleToDistributor">申请配送商</el-button>
              </el-form-item>
            </el-col>
          </el-row>

        </el-col>

        <el-col :span="24">
          <el-form-item label="配送费" prop="distributePrice">
            <distribute-price-popover ref="pricePopoverRef" :datas="{
                productId: openForm.productId,
                distributeId: openForm.distributeId,
                region:rowData.region,
                agentProductId:rowData.id
                }" position="bottom-start" @confirm="selectPrice">
              <div style="display:flex;flex-wrap:nowrap;">
                <el-select v-model="openForm.distributePrice"
                  :disabled="openForm.productId&&openForm.distributeId?false:true" path="matching" placeholder="选择配送费"
                  style="flex:1;" @change="distributePriceChange" @focus="priceFocus">
                  <template #empty />
                </el-select>
                <div v-if="distributePriceInfo?.computeMode==='固定价格'">
                  <span v-if="openForm.sellUnit" style="margin-left:4px;">
                    元 / {{ getLabel('sell_unit', openForm.sellUnit) }}
                  </span>
                </div>
                <div v-if="distributePriceInfo?.computeMode==='终端价百分比'">%终端价</div>
              </div>
            </distribute-price-popover>
          </el-form-item>
        </el-col>

      </el-row>

      <el-row gutter="40">
        <el-col :span="24">
          <item-title title="配送终端列表" />
        </el-col>

        <el-col :span="24" style="margin-bottom: 20px">
          <el-row :gutter="40">
            <el-col :span="8">
              <el-button size="small" type="primary" @click="handlAdd">添加终端</el-button>
              <el-button class="main-btn" size="small" @click="handlDele(null,1)">全部删除</el-button>
            </el-col>
            <el-col :span="6">
              <span style="margin-right:30px">没找到终端</span>
              <el-button type="text" @click="handleTo">创建终端</el-button>
            </el-col>
          </el-row>
        </el-col>

        <el-col :span="24">
          <el-form-item label-width="0px" prop="tableData">
            <el-table :data="openForm.tableData" border class="tableForm" header-cell-class-name="table-header"
              max-height="300px">

              <el-table-column align="center" header-align="center" label="终端名称" prop="terminalName">
                <template #default="scope">
                  <!-- :rules="{ required: true, message: '请选择终端名称', trigger: 'change'}" -->
                  <el-form-item :prop="'tableData.' + scope.$index + '.terminalName'" :rules="rules.terminalName"
                    label-width="0px" style="margin-top:14px">
                    <el-autocomplete v-model="scope.row.terminalName" :fetch-suggestions="querySearchTerminal"
                      :loading="false" placeholder="请输入终端名称" size="mini" style="width: 100%" placement="top"
                      @select="(val)=>handleSelecTerminal(val, scope.$index)">
                      <template #default="{ item }">
                        <div class="distributeName">{{ item.terminalName }}</div>
                      </template>
                    </el-autocomplete>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column align="center" header-align="center" label="终端类型" prop="type">
                <template #default="scope">
                  {{ getLabel('app_mode', scope.row.terminalType) }}
                </template>
              </el-table-column>

              <el-table-column align="center" header-align="center" label="所在地区" show-overflow-tooltip>
                <template #default="scope">
                  {{ scope.row.provinceName }}{{ scope.row.cityName }}{{ scope.row.areaName }}
                </template>
              </el-table-column>

              <el-table-column align="center" header-align="center" label="终端价(元)">
                <!-- :rules="{ required: true, message: '请选择终端价', trigger: 'change'}" -->
                <template #default="scope">
                  <el-form-item :prop="'tableData.' + scope.$index + '.terminalPrice'" :rules="rules.terminalPrice"
                    label-width="0px" style="margin-top:14px">
                    <app-price-popover :ref="(el)=>{priceProp(el,scope)}" :props-product="scope.row.propData"
                      position="top-start" @confirm="(val) => {priceConfirm(val,scope)}">
                      <el-select v-model="scope.row.terminalPrice" placeholder="请选择终端价" size="mini"
                        @focus="refFocus(scope)">
                        <template #empty />
                      </el-select>
                    </app-price-popover>
                  </el-form-item>

                </template>
              </el-table-column>

              <el-table-column align="center" header-align="center" label="操作">
                <template #default="scope">
                  <el-button class="delete-text-btn" type="text" @click="handlDele(scope.$index,2)">删除</el-button>
                </template>
              </el-table-column>

            </el-table>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>

    <template #footer>
      <div class="dialog-footer" style="display:flex;justify-content:center;align-items:center;">
        <el-button class="border-btn" size="small" style="margin-right: 20px;" @click="close">取消</el-button>
        <el-button class="main-btn" size="small" type="primary" @click="handlSubmit">提交审核</el-button>
      </div>
    </template>

    <create-distributor ref="distributorDialog" />

    <rule-form ref="ruleFormDialog" :sub="{boole:false, title: '保存'}" type-str="create" form-type="2" />

  </el-dialog>

</template>

<script>
import {
  defineAsyncComponent,
  getCurrentInstance,
  inject,
  reactive,
  toRefs,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";

export default {
  props: {
    tradePrice: {
      type: Number,
      default: 0,
    },
  },
  components: {
    distributePricePopover: defineAsyncComponent(() =>
      import("../../../modules/distributePricePopover.vue")
    ),
    ruleForm: defineAsyncComponent(() =>
      import("@CRM/views/marketing/customer/terminal/modules/ruleForm.vue")
    ),
    createDistributor: defineAsyncComponent(() =>
      import(
        "@CRM/views/distributorManagement/applyDistributors/modules/createDistributor.vue"
      )
    ),
  },
  setup(props, context) {
    const validateTable = (rule, value, callback) => {
      if (data.openForm.tableData.length === 0) {
        callback(new Error("至少添加一条配送信息"));
      } else {
        callback();
      }
    };
    const validateTerminalPrice = (rule, value, callback) => {
      var index = rule.field.split(".")[1];
      var terminalPrice = data.openForm.tableData[index].terminalPrice;
      console.log(terminalPrice,props.tradePrice);
      if (terminalPrice === "" || terminalPrice === 0 ) {
        callback(new Error("终端价为空或者为0"));
      } else {
         console.log(terminalPrice,props.tradePrice,"-----------");
        if (terminalPrice < Number(props.tradePrice)) {
          callback(new Error("终端价不能小于交易价"));
        } else {
          callback();
        }
      }
    };

    const validateTerminalName = (rule, value, callback) => {
      var index = rule.field.split(".")[1];
      console.log(value === "");
      if (value === "") {
        callback(new Error("终端名称不能为空"));
      } else {
        var id = data.openForm.tableData[index].id;
        var tableindex = data.openForm.tableData.findIndex((a) => a.id === id);
        if (tableindex != -1 && tableindex != index) {
          callback(new Error("终端名称不能重复"));
        } else {
          callback();
        }
      }
    };
    const store = useStore();
    const user = store.getters["user/userInfo"];
    const api = inject("api");
    const router = useRouter();
    const route = useRoute();
    const currentInstance = getCurrentInstance();
    const data = reactive({
      openBoole: false,
      openForm: {
        tableData: [],
        productId: 0,
        rddType: "2",
        distributeId: "",
        distributeName: "",
        distributePrice: "",
        distributeDetailId: "",
        sellUnit: "",
        distributeServerNo: "",
        distributeRegion: [],
      },
      distributes: [],
      rowData: null,
      addTerminalRef: null,
      openRef: null,
      priceRef: {},
      distributePriceInfo: null,
      pricePopoverRef: null,
      rules: {
        // tableData: [
        //   { required: true, validator: validateTable, trigger: "blur" },
        // ],
        distributeId: [
          { required: true, message: "请选择配送商", trigger: "change" },
        ],
        distributePrice: [
          { required: true, message: "请选择配送服务", trigger: "change" },
        ],
        terminalPrice: [{ validator: validateTerminalPrice, trigger: "change" }],
        terminalName: [{ validator: validateTerminalName, trigger: "change" }],
      },
      distributorDialog: null,
      ruleFormDialog: null,
    });

    //关闭弹框
    const close = () => {
      data.openBoole = false;
      data.openRef.clearValidate();
      data.openRef.resetFields();
    };

    //打开弹框
    const open = (row) => {
      data.rowData = row;
      data.openForm.productId = row?.productId;
      getDistributors();
      data.openBoole = true;
    };

    //获取配送商
    const getDistributors = () => {
      api.distributors
        .PRODUCT_FOR_DISTRIBUTORS_LIST({
          productId: data.rowData.productId,
        })
        .then((res) => {
          if (!res.code) {
            data.distributes = res.data.list;
          }
        });
    };

    //配送商change
    const distributesChange = (val) => {
      let obj = data.distributes.find((a) => a.id == val);
      data.openForm.distributeName = obj.distributeName;
    };

    //打开配送费
    const priceFocus = (val) => {
      if (val) {
        data.pricePopoverRef.openPopover();
      }
    };

    //获取配送费
    const selectPrice = (val) => {
      data.distributePriceInfo = val;
      data.openForm.distributeDetailId = val?.id;
      data.openForm.distributeServerNo = val?.distributeServeNo;
      data.openForm.distributePrice = val?.distributePrice;
      data.openForm.sellUnit = val?.sellUnit;
      data.openForm.distributeRegion = val?.region;
    };

    //申请配送商
    const handleToDistributor = () => {
      // window.open(`#/baseInfo/customer/contractedDistributor`);
      data.distributorDialog.open();
    };

    //删除配送终端
    const handlDele = (index, num) => {
      if (num === 1) {
        data.openForm.tableData = [];
      }
      if (num === 2) {
        data.openForm.tableData.splice(index, 1);
      }
    };

    //创建终端
    const handleTo = () => {
      // window.open(
      //   `#/marketing/cooperationInformation/serviceTerminal?type=direct`
      // );
      data.ruleFormDialog.open();
    };

    //添加配送信息
    const handlAdd = () => {
      let a = {
        terminalName: "",
        terminalType: "",
        provinceName: "",
        cityName: "",
        areaName: "",
        terminalPrice: undefined,
      };
      Promise.all([
        handlValidateField("distributeId"),
        handlValidateField("distributePrice"),
      ]).then(() => {
        data.openForm.tableData.push(a);
      });
    };

    const handlValidateField = (val) => {
      return new Promise((resolve, reject) => {
        data.openRef.validateField(val, (valid) => {
          if (!valid) {
            resolve();
          } else {
            return false;
          }
        });
      });
    };

    //获取终端
    const querySearchTerminal = async (queryString, cb) => {
      let a = {
        productId: data.rowData?.productId,
        distributeId: data.openForm.distributeId,
        terminalType: data.rowData?.terminalType,
        region: data.openForm.distributeRegion,
        agentRegion: data.rowData.region,
        terminalName: queryString,
      };
      let results = [];
      let res = await api.marketingMatching.REGIONAL_TERMINAL_LIST(a);
      if (res.code === 0) {
        results = res.data.list || [];
      }
      cb(results);
    };

    //终端赋值
    const handleSelecTerminal = (val, index) => {
      val.propData = {
        terminalId: val.id,
        terminalType: val.terminalType,
        productId: data.rowData.productId,
        region: data.rowData.region,
      };
      val.terminalPrice =
        val.terminalPrice === 0 ? "" : val.terminalPrice;
      data.openForm.tableData[index] = val;
    };

    const priceProp = (el, scope) => {
      data.priceRef[scope.$index] = el;
    };

    const refFocus = (scope) => {
      data.priceRef[scope.$index].openPopover();
    };

    //选择终端价
    const priceConfirm = (val, scope) => {
      data.openForm.tableData[scope.$index].productPriceId = val.id;
      data.openForm.tableData[scope.$index].app_price = val.terminalPrice;
      data.openForm.tableData[scope.$index].terminalPrice = Number(
        val.terminalPrice
      );
    };

    //提交
    const handlSubmit = () => {
      data.openRef.validate((valid) => {
        if (valid) {
          let obj = {
            agentName: data.rowData.agentName,
            producer: data.rowData.producer,
            agentProductNumber: data.rowData.agentProductNumber,
            agentProductId: Number(data.rowData.id),
            productId: Number(data.rowData.productId),
            productName: data.rowData.productName,
            productPopularName: data.rowData.productPopularName,
            packSpecs: data.rowData.packSpecs,
            sellUnit: data.openForm.sellUnit,
            rddType: data.openForm.rddType,
            distributeId: Number(data.openForm.distributeId),
            distributeName: data.openForm.distributeName,
            distributeServerId: Number(data.openForm.distributeDetailId),
            distributeServerNo: data.openForm.distributeServerNo,
            terminalType: data.rowData.terminalType,
            headName: user.realName,
            headId: Number(user.ID),
            terminals: data.openForm.tableData,
            tradePrice: data.rowData.tradePrice,
            region: data.rowData.region,
          };
          handlOpenForm(obj);
        }
      });
    };

    const handlOpenForm = (val) => {
      api.signedAgent
        .DISTRIBUTE_CONTRACT_DETAIL_ASSOCIATION(val)
        .then((res) => {
          if (!res.code) {
            currentInstance.proxy.customMessage({
              type: "success",
              message: "提交成功",
            });
            context.emit("success");
            close();
          } else {
            currentInstance.proxy.customMessage({
              type: "error",
              message: res.msg,
            });
          }
        });
    };

    return {
      ...toRefs(data),
      close,
      open,
      handlDele,
      handleTo,
      handlAdd,
      handlSubmit,
      getDistributors,
      priceConfirm,
      priceProp,
      refFocus,
      distributesChange,
      priceFocus,
      selectPrice,
      querySearchTerminal,
      handleSelecTerminal,
      handlOpenForm,
      handleToDistributor,
    };
  },
};
</script>

<style lang="scss" scoped>
// :deep(.tableForm .el-form-item--small.el-form-item) {
//   margin-bottom: 0 !important;
// }
</style>